import com.master.game.tutorials.osgi.ds.quoteAPI.IQuoteService;

public class QuoteConsumer {
	private IQuoteService service;

	Thread consumerThread;
	
	public QuoteConsumer() {
		consumerThread = new Thread(){
			@Override
			public void run() {
				for (int i=0;i<20;i++){
					// print a quote 10 times
					System.out.println(service.getQuote());
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
	}

	public void quote() {
		System.out.println(service.getQuote());
	}
	
	// Method will be used by DS to set the quote service
	public synchronized void setQuote(IQuoteService service) {
		System.out.println("Service was set. Thank you DS!");
		this.service = service;
		consumerThread.start();
	}

	// Method will be used by DS to unset the quote service
	public synchronized void unsetQuote(IQuoteService service) {
		System.out.println("Service was unset. Why did you do this to me?");
		if (this.service == service) {
			//stop the thread
			consumerThread.interrupt();
			this.service = null;
		}
	}
}
